package shlib

import (
	"errors"
	"sync/atomic"
)

type ServRequest struct {
	Command string
	Data    Any
}

type IServlet interface {
	OnStart()
	OnRequest(req *ServRequest)
	OnStop()
}

type BaseServlet struct {
	isRunning int64
	impl      IServlet
}

func (this *BaseServlet) Start() error {
	if !atomic.CompareAndSwapInt64(&this.isRunning, 0, 1) {
		return errors.New("servlet is already running")
	}

	if this.impl != nil {
		this.impl.OnStart()
	}

	return nil
}

func (this *BaseServlet) Stop() {
	if !atomic.CompareAndSwapInt64(&this.isRunning, 1, 0) {
		return
	}

	if this.impl != nil {
		this.impl.OnStop()
	}
}

func (this *BaseServlet) IsRunning() bool {
	return this.isRunning == 1
}
